<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="问卷的标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入问卷的标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布状态" prop="publishStatus">
        <el-select v-model="queryParams.publishStatus" placeholder="请选择发布状态" clearable>
          <el-option
            v-for="dict in dict.type.publish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['questionnaire:questionnaire:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['questionnaire:questionnaire:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['questionnaire:questionnaire:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['questionnaire:questionnaire:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionnaireList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="问卷id" align="center" prop="questionnaireId" />
      <el-table-column label="标题" align="center" prop="title">
       <template #default="{ row }">
         <span style="color: goldenrod; font-weight: bold;">{{ row.title }}</span>
      </template>
     </el-table-column>
      <el-table-column label="图片" align="center" width="200">
      <template slot-scope="scope">
        <img :src="scope.row.picture" alt="图片" style="width: 100%; height: auto;">
      </template>
    </el-table-column>

    <el-table-column label="问卷的描述" align="center" prop="description">
       <template #default="{ row }">
         <span style="color:deepskyblue; font-weight: bold;">{{ row.description}}</span>
      </template>
     </el-table-column>

      <el-table-column label="问卷创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

  <el-table-column label="发布状态" align="center" prop="publishStatus">
  <template slot-scope="scope">
    <div v-if="scope.row.status === 3">
      <dict-tag :options="dict.type.publish_status" :value="form.publishStatus=1" />
    </div>
    <div v-else>
      <dict-tag :options="dict.type.publish_status" :value="scope.row.publishStatus" />
      </div>
    </template>
 </el-table-column>

      <el-table-column prop="status" label="审批状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hdh_status" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['questionnaire:questionnaire:edit']"
            v-show="scope.row.status==0"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['questionnaire:questionnaire:edit']"
            v-show="scope.row.status==1"
          >打回修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['questionnaire:questionnaire:remove']"
          >删除</el-button>

          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-single"
            @click="handlequestionnairesSubmit(scope.row.questionnaireId)"
            v-hasPermi="['questionnaires:questionnaires:questionnairesSubmit']"
            v-show="scope.row.status==0|scope.row.status==1"
          >提交问卷发布</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-data-analysis"
            @click="handleShowStatistics(scope.row.questionnaireId)"
          >统计图表</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="`问卷 ${selectedQuestionnaireTitle} 的统计图表`" :visible.sync="statisticsDialogVisible" width="80%">
      <StatisticsChart :questionnaireId="selectedQuestionnaireId" />
    </el-dialog>


<el-dialog :title="questionnaireDetails.title" :visible.sync="viewDialogVisible" width="600px">
  <div class="questionnaire-title" style="text-align: center; font-weight: bold; font-size: 18px; margin-bottom: 20px;">
    {{ questionnaireDetails.title }}
  </div>
  <el-form :model="questionnaireDetails" label-width="120px" class="questionnaire-form">

    <div v-for="(question, index) in questionnaireDetails" :key="question.questionId" class="question-item">
      <el-form-item :label="'问题 ' + (index + 1)" class="question-form-item">
        <div class="question-text">{{ question.questionText }}</div>

        <!-- 根据问题类型显示不同的控件 -->
        <div v-if="question.questionType === '0'"> <!-- 单选 -->
          <el-radio-group v-model="question.selectedOption" class="option-group">
            <el-radio
              v-for="option in question.options"
              :key="option.optionId"
              :label="option.optionId"
            >{{ option.optionText }}</el-radio>
          </el-radio-group>
        </div>

        <div v-else-if="question.questionType === '1'"> <!-- 多选 -->
          <el-checkbox-group v-model="question.selectedOptions" class="option-group">
            <el-checkbox
              v-for="option in question.options"
              :key="option.optionId"
              :label="option.optionId"
            >{{ option.optionText }}</el-checkbox>
          </el-checkbox-group>
        </div>


        <div v-else-if="question.questionType === '2'">
          <el-input v-model="question.textAnswer" placeholder="请输入答案" />
        </div>
      </el-form-item>
    </div>


    <div slot="footer" class="dialog-footer">
      <el-button @click="viewDialogVisible = false" size="small">关 闭</el-button>
    </div>

  </el-form>
</el-dialog>






    <!-- 添加或修改问卷信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问卷的标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入问卷的标题" />
        </el-form-item>
        <el-form-item label="问卷的描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="图片" prop="picture" v-if="false">
          <el-input v-model="form.picture" placeholder="输入图片地址"/>
        </el-form-item>

      <el-image
         style="width: 300px; height: 300px"
          :src="url"
          :fit="fit" ref="imageId" >
        </el-image>


      <el-upload
        ref="uploadFile"
        :limit="1"
        accept=".bmp,.jpg,.jpeg,.png,gif"
        :headers="uploadData.headers"
        :action="uploadData.url"
        :disabled="uploadData.isUploading"
        :on-progress="handleFileUploadDataProgress"
        :on-success="handleFileDataSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <span>仅允许导入bmp、jpg、jpeg、gif、png格式文件。</span>
      </el-upload>

       <el-button type="primary" @click="submitFileFormImage">上传图片</el-button>

        <el-divider content-position="center">问题信息信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddZxhQuestion">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteZxhQuestion">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="zxhQuestionList" :row-class-name="rowZxhQuestionIndex" @selection-change="handleZxhQuestionSelectionChange" ref="zxhQuestion">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="问题名称" prop="questionText">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.questionText"
                type="textarea"
                placeholder="请输入内容"
                :rows="4"
              />
            </template>
            </el-table-column>
          <el-table-column label="问题的类型" prop="questionType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.questionType" placeholder="请选择问题的类型">
                <el-option
                  v-for="dict in dict.type.question_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestionnaire, getQuestionnaire, delQuestionnaire, addQuestionnaire, updateQuestionnaire ,getQuestionnaireDetails, submitquestionnaire} from "@/api/questionnaire/questionnaire";
import { getToken } from "@/utils/auth";
import StatisticsChart from '@/views/questionnaire/StatisticsChart.vue';
export default {
//  name: "Questionnaire",
  name: "QuestionnaireView",
  dicts: ['question_type', 'publish_status','hdh_status'],
  components: {
    StatisticsChart
  },
  data() {

    return {
      statisticsDialogVisible: false,
      selectedQuestionnaireId: null,
      selectedQuestionnaireTitle: '',
      viewDialogVisible: false,
      questionnaireDetails: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedZxhQuestion: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问卷信息表格数据
      questionnaireList: [],
      // 问题信息表格数据
      zxhQuestionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

        // 图片导入参数
        uploadData:
        {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/questionnaire/questionnaire/uploadMinio"
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        description: null,
        publishStatus: null,
      },
      // 表单参数
      form: {},

      // 表单校验
      rules:
       {
        title: [
          { required: true, message: "问卷的标题不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "问卷的描述不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "问卷创建时间不能为空", trigger: "blur" }
        ],
      },

      url: '',
      fit: 'contain',

         };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询问卷信息列表 */
    getList() {
      this.loading = true;
      listQuestionnaire(this.queryParams).then(response => {
        this.questionnaireList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        questionnaireId: null,
        title: null,
        description: null,
        createTime: null,
        publishStatus: null,
        updatedTime: null,
        createBy: null,
        version: null,
        picture: null
      };
      this.zxhQuestionList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.questionnaireId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加问卷信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const questionnaireId = row.questionnaireId || this.ids
      getQuestionnaire(questionnaireId).then(response => {
        this.form = response.data;
        this.zxhQuestionList = response.data.zxhQuestionList;
        this.open = true;
        this.title = "修改问卷信息";
        this.url = this.form.picture;
        console.log('图片 URL:', this.url);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.zxhQuestionList = this.zxhQuestionList;
          if (this.form.questionnaireId != null) {
            updateQuestionnaire(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestionnaire(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const questionnaireIds = row.questionnaireId || this.ids;
      this.$modal.confirm('是否确认删除问卷信息编号为"' + questionnaireIds + '"的数据项？').then(function() {
        return delQuestionnaire(questionnaireIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 问题信息序号 */
    rowZxhQuestionIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 问题信息添加按钮操作 */
    handleAddZxhQuestion() {
      let obj = {};
      obj.questionText = "";
      obj.questionType = "";
      obj.createTime = "";
      this.zxhQuestionList.push(obj);
    },
    /** 问题信息删除按钮操作 */
    handleDeleteZxhQuestion() {
      if (this.checkedZxhQuestion.length == 0) {
        this.$modal.msgError("请先选择要删除的问题信息数据");
      } else {
        const zxhQuestionList = this.zxhQuestionList;
        const checkedZxhQuestion = this.checkedZxhQuestion;
        this.zxhQuestionList = zxhQuestionList.filter(function(item) {
          return checkedZxhQuestion.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleZxhQuestionSelectionChange(selection) {
      this.checkedZxhQuestion = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('questionnaire/questionnaire/export', {
        ...this.queryParams
      }, `questionnaire_${new Date().getTime()}.xlsx`)
    },


async handleView(row) {
  const questionnaireId = row.questionnaireId;
  try {
    const response = await getQuestionnaireDetails(questionnaireId);
    console.log('API Response:', response);

    if (Array.isArray(response)) {
      // 数据合并处理
      let questions = [];

      response.forEach(item => {
        // 查找该问题是否已存在
        let question = questions.find(q => q.questionId === item.questionId);
        if (!question) {
          // 如果该问题不存在，则新增
          question = {
            questionId: item.questionId,
            title: item.title,
            questionText: item.questionText,
            questionType: item.questionType,
            options: [],
            selectedOption: null, // 默认没有选项被选中
            selectedOptions: []   // 多选时保存选中的多个选项
          };
          questions.push(question);
        }

        // 将选项添加到问题的 options 数组中
        question.options.push({
          optionId: item.optionId,
          optionText: item.optionText
        });
      });

      this.questionnaireDetails = questions;
      this.viewDialogVisible = true;
    } else {
      this.$message.error("获取到的问卷详细信息格式不正确");
      console.log('Unexpected response structure:', response);
    }
  } catch (error) {
    console.error(error);
    this.$message.error("获取问卷详细信息失败: " + error.message);
  }
},

     // 文件上传中处理
     handleFileUploadDataProgress(event, file, fileList)
     {
      console.log(getToken());
      console.log(event);
      console.log(file+"333");
      console.log(fileList+"333");
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileDataSuccess(response, file, fileList)
    {
       console.log(response);
       console.log(response.msg);
       console.log(file+"444");
       console.log(fileList+"555");
      this.uploadData.open = false;
      this.uploadData.isUploading = false;
      this.$refs.uploadFile.clearFiles();
      this.form.picture=response.msg;

       this.url=this.form.picture;

      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "上传图片成功！" + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileFormImage() {
      this.$refs.uploadFile.submit();
    },
    handlequestionnairesSubmit(questionnaireId){
      console.log('Submitting questionnaire with ID:', questionnaireId);
      submitquestionnaire(questionnaireId).then(response => {
          console.log(response)
          this.getList();
          this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "提交申请成功！" + "</div>", "提示框", { dangerouslyUseHTMLString: true });
       });
   },

   handleShowStatistics(questionnaireId) {
      this.selectedQuestionnaireId = questionnaireId;
      const selectedQuestionnaire = this.questionnaireList.find(q => q.questionnaireId === questionnaireId);
      this.selectedQuestionnaireTitle = selectedQuestionnaire ? selectedQuestionnaire.title : '';
      this.statisticsDialogVisible = true;
    }

  }
};
</script>

<style>
.custom-dialog .el-dialog__body {
  background-color:beige /* 设置整个对话框背景为淡黄色 */
}

.questionnaire-form {
  padding: 10px;
  background-color: rgb(225, 242, 255); /* 设置表单背景色为淡黄色 */
}

.question-item {
  margin-bottom: 10px; /* 缩小每个问题项之间的行距 */
  background-color: rgb(225, 244, 255); /* 设置每个问题项的背景色 */
  padding: 10px;
  border-radius: 4px;
}

.question-item:last-child {
  margin-bottom: 2px; /* 缩小最后一个问题和下一个问题之间的间距 */
}

.question-text {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 6px; /* 缩小问题文本与选项之间的间距 */
}

.option-group {
  display: flex;
  flex-direction: column;
}

.option-group .el-radio,
.option-group .el-checkbox {
  margin-bottom: 8px; /* 增加选项之间的间距 */
}

.text-area {
  width: 100%;
  margin-top: 6px; /* 调整文本框和选项之间的间距 */
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
}
</style>
